package me.zhengjie.pool.ipproxy;


import com.alibaba.fastjson.JSONObject;
import me.zhengjie.pool.excutor.CustomExecutorService;
import me.zhengjie.pool.ipproxy.domain.IPInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Date 创建时间： 2021-01-18 15:58
 * @Author 作者姓名: WuNengDeShiXiong
 * @Version 1.0
 * @Copyright Copyright by
 * @Direction 类说明
 */
@Component
@Lazy(value = false)
@EnableScheduling
public class IpSourceValid {

    private final static Logger logger = LoggerFactory.getLogger( IpSourceValid.class ) ;

    @Autowired
    private RedisTemplate redisTemplate;

    /****
     * 已有的代理池，则需要30秒刷新一次，不可用的IP代理池、全部丢弃
     */
    //@Scheduled(cron = "0 * * * * ?")
    void update() {
        logger.info( " redis IP代理池检测开始 ....................."  );
        List<String> range = redisTemplate.opsForList().range("ip", 0, -1);
        for (String ipInfoJson : range) {
            //线程池检测-代理IP池-有效的IP有哪些
            CustomExecutorService.execute(new Thread() {
                @Override
                public void run() {
                    IPInfo ipInfo = JSONObject.parseObject( ipInfoJson , IPInfo.class ) ;
                    //使用时-要求偏低,不可用时从Redis删除
                    Boolean useLess = IpInvalidUtils.useless( ipInfo.getIp() , Integer.parseInt(ipInfo.getPort() ) , false ) ;
                    if ( useLess ) {
                        logger.info( " {} 从redis移除" , ipInfoJson );
                        redisTemplate.opsForList().remove("ip", 0, ipInfoJson );
                    }
                }
            }) ;
        }
        logger.info( " redis IP代理池检测结束 ....................."  );
    }

}
